package com.example.himalaya2;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya2.adapters.DetailListAdapter;
import com.example.himalaya2.base.BaseActivity;
import com.example.himalaya2.base.BaseApplication;
import com.example.himalaya2.interfaces.IAlbumDetailViewCallback;
import com.example.himalaya2.interfaces.IPlayerCallback;
import com.example.himalaya2.presenters.AlbumDetailPresenter;
import com.example.himalaya2.presenters.PlayerPresenter;
import com.example.himalaya2.utils.ImageBlur;
import com.example.himalaya2.utils.LogUtil;
import com.example.himalaya2.views.RoundRectImageView;
import com.example.himalaya2.views.UILoader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class DetailActivity extends BaseActivity implements IAlbumDetailViewCallback, DetailListAdapter.ItemClickListener, IPlayerCallback {

    private static final String TAG = "DetailActivity";
    private ImageView mLargeCover;
    private RoundRectImageView mSmallCover;
    private TextView mAlbumTitle;
    private TextView mAlbumAuthor;
    private  int mCurrentPage = 1;
    private RecyclerView mDetailList;

    private AlbumDetailPresenter mAlbumDetailPresenter;
    private DetailListAdapter mDetailListAdapter;
    private FrameLayout mDetailListContainer;
    private UILoader mUiLoader;
    private ImageView mPlaControlBtn;
    private TextView mPlayControlTv;
    private PlayerPresenter mPlayerPresenter;
    private List<Track> mCurrentTrack = null;
    private final static int DEFAULT_PLAY_INDEX = 0;
    private RefreshLayout mRefreshLayout;
    private boolean mIsLoadMore = false;
    private String mCurrentTitle = null;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        initView();

        // 这个是专辑详情的present
        mAlbumDetailPresenter  = AlbumDetailPresenter.getInstance();
        mAlbumDetailPresenter.registerViewCallback(this);
        // 这个是播放器的presenter
        mPlayerPresenter = PlayerPresenter.getInstance();
        mPlayerPresenter.registerViewCallback(this);
        upDatePlayState(mPlayerPresenter.isPlay());
        initListener();
    }

    private void initListener() {
        if (mPlaControlBtn != null) {
            mPlaControlBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    LogUtil.d(TAG,"mPlaControlBtn onClick");
                    
                    if (mPlayerPresenter != null) {
                        // 判断播放器是否拥有播放的列表
                        // todo
                        boolean has = mPlayerPresenter.hasPlayList();
                        if (has) {
                            handlePlayControl();
                        } else {
                           handleNoPlayList();
                        }
                      
                    }
                }
            });
        }
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                LogUtil.d(TAG,"setOnRefreshListener");
                BaseApplication.getsHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DetailActivity.this,"刷新成功",Toast.LENGTH_SHORT).show();
                        mRefreshLayout.finishRefresh();
                    }
                }, 2000);
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (mAlbumDetailPresenter != null) {
                    mAlbumDetailPresenter.loadMore();
                    mIsLoadMore = true;
                }
              /*  LogUtil.d(TAG,"setOnLoadMoreListener");
                BaseApplication.getsHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DetailActivity.this,"加载更多成功",Toast.LENGTH_SHORT).show();
                        mRefreshLayout.finishLoadMore();
                    }
                }, 2000);*/
            }
        });
    }

    /*
    * 当播放器里面没有播放内容时，我们就要进行处理
    * */
    private void handleNoPlayList() {
        mPlayerPresenter.setPlayList(mCurrentTrack,DEFAULT_PLAY_INDEX);
    }


    private void handlePlayControl() {
        // 控制播放器的状态
        if (mPlayerPresenter.isPlay()) {
            // 正在播放 ，就暂停
            mPlayerPresenter.pause();
        } else {
            // 没有在播放 就播放
            mPlayerPresenter.play();
        }
    }

    private void initView() {
        mDetailListContainer = this.findViewById(R.id.detail_list_container);

        if (mUiLoader == null) {
            mUiLoader = new UILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    LogUtil.d(TAG,"74");
                    return CreateSuccessView(container);
                }
            };
        }
        LogUtil.d(TAG," BEFORE mDetailListContainer.removeAllViews();");
        mDetailListContainer.removeAllViews();
        LogUtil.d(TAG,"AFTER mDetailListContainer.removeAllViews();");
        mDetailListContainer.addView(mUiLoader);

        mLargeCover = this.findViewById(R.id.iv_large_cover);
        mSmallCover = this.findViewById(R.id.viv_small_cover);
        mAlbumTitle = this.findViewById(R.id.tv_album_title);
        mAlbumAuthor = this.findViewById(R.id.tv_album_author);
        LogUtil.d(TAG,"initView()");
        // 播放控制的 图标
        mPlaControlBtn = this.findViewById(R.id.detail_play_control);
        mPlayControlTv = this.findViewById(R.id.play_control_text);
        mRefreshLayout = (RefreshLayout)findViewById(R.id.refresh_layout);
    }

    private View CreateSuccessView(ViewGroup container) {
        LogUtil.d(TAG,"BEFORE ");
        View detailListView = LayoutInflater.from(this).inflate(R.layout.item_detail_list,container,false);
        mDetailList = detailListView.findViewById(R.id.album_detail_list);
        // RecycleListView 的使用
        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mDetailList.setLayoutManager(layoutManager);
        // 设置适配器
        mDetailListAdapter = new DetailListAdapter();
        mDetailList.setAdapter(mDetailListAdapter);
        // 设置上下间距
        mDetailList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull @NotNull Rect outRect, @NonNull @NotNull View view, @NonNull @NotNull RecyclerView parent, @NonNull @NotNull RecyclerView.State state) {
                outRect.top=5;
                outRect.bottom=5;
            }
        });
        LogUtil.d(TAG,"CreateSuccessView");
        mDetailListAdapter.setItemClickListener(this);
        return detailListView;
    }

    @Override
    public void onDetailListLoaded(List<Track> tracks) {
        LogUtil.d(TAG,"onDetailListLoaded");
        if (mIsLoadMore&&mRefreshLayout!=null) {
            mRefreshLayout.finishLoadMore();
            mIsLoadMore = false;
        }

        this.mCurrentTrack = tracks;
        // 判断数据结果，根据结果控制UI显示
        if (tracks == null||tracks.size()==0) {
            if (mUiLoader != null) {
                mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
            }
        }
        if (mUiLoader != null) {
            mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);
        }
        // 更新UI数据
        mDetailListAdapter.setData(tracks);

    }

    @Override
    public void onAlbumLoaded(Album album) {
        // 获取专辑的详情内容
        mAlbumDetailPresenter.getAlbum((int) album.getId(),mCurrentPage);
        // 拿到数据  ，显示loading状态
        if (mUiLoader != null) {
            mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
        }
        if (mAlbumTitle != null) {
            mAlbumTitle.setText(album.getAlbumTitle());
        }
        if (mAlbumAuthor != null) {
            mAlbumAuthor.setText(album.getAnnouncer().getNickname());
        }
        if (mLargeCover != null) {
            Picasso.with(this).load(album.getCoverUrlLarge()).into(mLargeCover, new Callback() {
                @Override
                public void onSuccess() {
                    Drawable drawable = mLargeCover.getDrawable();
                    if (drawable!=null) {
                        ImageBlur.makeBlur(mLargeCover,DetailActivity.this);
                    }
                }

                @Override
                public void onError() {
                    LogUtil.d(TAG,"onError()");
                }
            }); // 异步的
            // 做毛玻璃效果
        }
        if (mSmallCover != null) {
            Picasso.with(this).load(album.getCoverUrlSmall()).into(mSmallCover);
        }
    }

    @Override
    public void onNetworkError(int i, String s) {
        // 请求发生错误，显示网络异常的状态
        mUiLoader.updateStatus(UILoader.UIStatus.NETWORK_ERROR);
    }

    @Override
    public void onLoaderMoreFinish(int size) {
        if (size > 0) {
            Toast.makeText(this,"成功加载"+size+"条数据",+Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this,"没有更多的内容了",+Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRefreshFinish(int size) {

    }


    @Override
    public void onItemClicked(List<Track> detailData, int position) {
        // 设置播放列表 index
        PlayerPresenter playerPresenter= PlayerPresenter.getInstance();
        playerPresenter.setPlayList(detailData,position);  // 这里给了 当进入播放的时候的 播放列表和播放的位置
        // todo  跳转到播放器界面
        Intent intent = new Intent(this,PlayerActivity.class);
        startActivity(intent);
    }

    /*
    * 根据播放状态修改图标和文字
    * */
    private void upDatePlayState(boolean play) {
        // 修改图标为暂停的状态，文字为 正在播放

        if (mPlayControlTv != null && mPlaControlBtn!= null ) {
            mPlaControlBtn.setImageResource(play?R.drawable.selector_palyer_pause:R.drawable.selector_palyer_play);
            if (!play) {
                if (mCurrentTitle != null) {
                    mPlayControlTv.setText(mCurrentTitle);
                } else {
                    mPlayControlTv.setText(R.string.click_play_text);
                }
            }
        }
    }

    @Override
    public void onPLayStart() {
        upDatePlayState(true);
    }

    @Override
    public void onPlayPause() {
        // 修改图标为播放的状态  ,文字修改成已经暂停
        upDatePlayState(false);
    }

    @Override
    public void onPlayStop() {
        upDatePlayState(false);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> tracks) {

    }

    @Override
    public void onPlayModelChange(XmPlayListControl.PlayMode mode) {

    }

    @Override
    public void onProgressChange(long current, long title) {

    }

    @Override
    public void onADLoading() {

    }

    @Override
    public void onAdFinish() {

    }

    @Override
    public void onTrackUpdate(Track track, int position) {
        if (track != null) {
            String trackTitle = track.getTrackTitle();
            mCurrentTitle = trackTitle;
            if (!TextUtils.isEmpty(trackTitle)&& mPlayControlTv!=null) {
                mPlayControlTv.setText(trackTitle);
            }
        }
    }
}
